<template>
    <div class="add-order">
        <el-dialog v-model="showDialog" :title="`修改密码`" width="500px" :before-close="cancel">
            <el-form ref="ruleFormRef" :model="ruleForm.formData" :rules="rules" label-width="80px" class="demo-ruleForm">
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="ruleForm.formData.password" show-password placeholder="请输入密码" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel">取消</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="loading">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import {
  updatePassword
} from "@/api/product";
import type { FormInstance, FormRules } from 'element-plus'
const props = defineProps({
    showDialog: Boolean,
    modelData: {
        type: Object,
        default: {},
    },
});
const {modelData, showDialog} = toRefs(props)
const loading = ref(false)
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    formData: {
        id: '',
        password: '',
        name: ''
    },
})
const rules = reactive<FormRules>({
    password: [
        { required: true, message: '请输入密码', trigger: ['blur'] },
    ],
 
})
watch(
  () => showDialog.value,
  (showDialog) => {
    if(showDialog) {
       ruleForm.formData = {
            password: '',
            id:  modelData.value.id,
            name: modelData.value.storeName
        }
        console.log('enter', ruleForm.formData)
    }
  }
)

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            
            addMedalInfo()
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 修改密码
const addMedalInfo = async()=>{
  loading.value = true
  let rs: any = await updatePassword(ruleForm.formData)
  if(rs.code === 200) {
    ElMessage({
        message: `密码修改成功`,
        type: 'success',
    })
    confirm()
  }
  loading.value = false
    
}
const confirm = () => {
    emit("confirm");
    cancel()
};

const cancel = () => {
    ruleForm.formData = {
        id: '',
        password: '',
        name: ''
    }
    setTimeout(() => {
        ruleFormRef.value?.resetFields()
    }, 0);
    emit("cancel", 'showPassWordDialog');
}
const emit = defineEmits(["confirm", "cancel"]);
</script>

<style lang="scss" scoped>

</style>